class EventBus {
  // 存储的事件名称以及对应的监听数组
  events: object;

  constructor() {
    this.events = {};
  }

  /**
   * 解绑
   */
  private unbind(event, callback) {
    this.events[event].forEach(
      (e, i) => e === callback && this.events[event].splice(i, 1)
    );
  }

  emit(event: string, ...args) {
    (this.events[event] || []).forEach(e => e.apply(this, args));
  }

  /**
   * 只执行一次
   */
  once(event: string, callback: Function) {
    let cb = function (this: EventBus) {
      this.unbind(event, cb);
      return callback.apply(this, arguments);
    }
    this.on(event, cb);
  }

  /**
   * 给某事件名称增加监听回调
   */
  on(event: string, callback: Function) {

    if (typeof callback !== 'function') {
      throw new TypeError('请设置监听函数');
    }

    // 安排监听函数
    (this.events[event] = this.events[event] || []).push(callback);

    // 注销监听
    return () =>
      this.unbind(event, callback);
  }
}


export default EventBus;